// var app = require('./app.js')
var fs = require('fs')
var Student = require('./students.js')
var express = require('express')

// 1. 创建一个路由容器
var router = express.Router()

router.get('/students', function (req, res) {
    /* fs.readFile('./db.json', 'utf8', function (err, data) {
        if (err) {
            return res.status(500).send('Server error')
        }
        // console.log(data)
        var students = JSON.parse(data).students
        res.render('index.html', {
            fruits: [
                '苹果',
                '香蕉',
                '橘子'
            ],
            students: students
        })
    }) */
    Student.find(function (err, students) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.render('index.html', {
            fruits: [
                '苹果',
                '香蕉',
                '橘子'
            ],
            students: students
        })
    })
})
router.get('/students/new', function (req, res) {
    res.render('new.html')
})
router.post('/students/new', function (req, res) {
    // 1. 获取表单数据
    // 2. 处理
    //    将数据保存到 db.json 文件中用以持久化
    // 3. 发送响应
    // console.log(req.body)
    // var Student = req.body
    new Student(req.body).save(function (err) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.redirect('/students')
    })
})
router.get('/students/edit', function (req, res) {
    Student.findById(req.query.id.replace(/"/g, ''), function (err, student) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.render('edit.html', {
            student: student
        })
    })
})

router.post('/students/edit', function (req, res) {
    var id = req.body.id.replace(/"/g, '')
    Student.findByIdAndUpdate(id, req.body, function (err) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.redirect('/students')
    })
})
router.get('/students/delete', function (req, res) {
    var id = req.query.id.replace(/"/g, '')
    Student.findByIdAndRemove(id, function (err) {
        if (err) {
            return res.status(500).send('Server error')
        }
        res.redirect('/students')
    })
})


module.exports = router